Promises Chaining in Javascript




There may be some scenario in which we have to execute a list of asynchronous tasks one after the other. We can perform this scenario either by using callback or by using promise chaining or by using async/await. The first approach, using callback would lead to callback hell which is not advisable to use this method. The second approach, is using promise chaining which will be discussed in this article. The third approach, can be learned in the following link.

Each promise constructor will contain 2 parameters. One is resolve and the other is reject. Calling resolve function is used to return the success response and calling reject function will send an error response. In promise chaining, when resolve is called it passes the result to the next then block and it keeps on continuing until the last then block. If any error has occurred, then the error will be thrown to the catch block skipping the rest of the then blocks in the flow of promises.

Promise chaining, is simply chaining of promises one after the other.Lets see it with an example.

Output:

One

Two

Three

In the above program, there are three function one(), two() and three(). Each function will return a promise. When calling function one() it returns a string 'One' to resolve function. The string 'One' is passed as parameter to the then block and result is printed. Then function two() is called and returned. The function two() will return the string 'Two' to resolve function which is passed as parameter to the then block and result is printed. The same operation is continued for three() function call and forward the result to the then block and prints the result.

Lets modify the above program for handling the error condition by calling reject function.

Output:

One
Failed

In the above program one() function is called and that returns the result 'One' to the then block and then function two() is called which in turns call the reject function with 'Failed' string. Now the catch block will be called skipping the remaining then blocks.


Most Read